﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Wizard : MonoBehaviour
{
    Rigidbody2D rb;
    Animator anim;

    public GameObject fireObj;
    public GameObject player;
    public Transform shootPosition;
    public GameObject fireBall;

    public bool canFire;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        //Instantiate(fireObj, shootPosition.position, Quaternion.identity);
    }

    // Update is called once per frame
    void Update()
    {
        if(fireBall == null)
        {
            fireBall = GameObject.Find("FireBall(Clone)");
        }
    }

    void Fire()
    {
        if (fireBall == null && canFire)
        {
            anim.Play("Wizard_fire");
        }
    }

    public void FireBall()
    {
        Instantiate(fireObj, shootPosition.position, Quaternion.identity);
    }

    void PlayerDirection(Transform transform1,Transform transform2)
    {
        if (transform1.position.x > transform2.position.x)
        {
            transform2.localScale = new Vector3(-1, 1, 1);
        }
        else if (transform1.position.x < transform2.position.x)
        {
            transform2.localScale = new Vector3(1, 1, 1);
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            canFire = true;
            PlayerDirection(player.transform, this.transform);
            //Fire();
            StartCoroutine(Wait());
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        canFire = false;
    }

    void Idle()
    {
        anim.Play("Wizard_idle");
    }

    IEnumerator Wait()
    {
        Fire();
        yield return new WaitForSeconds(2);
        
    }

}
